package com.ytclub.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.ytclub.subject.common.entity.PageResult;
import com.ytclub.subject.common.enums.IsDeletedFlagEnum;
import com.ytclub.subject.common.util.IdWorkerUtil;
import com.ytclub.subject.common.util.LoginUtil;
import com.ytclub.subject.domain.convert.SubjectInfoConverter;
import com.ytclub.subject.domain.entity.SubjectInfoBO;
import com.ytclub.subject.domain.entity.SubjectOptionBO;
import com.ytclub.subject.domain.handle.SubjectTypeHandler;
import com.ytclub.subject.domain.handle.SubjectTypeHandlerFactory;
import com.ytclub.subject.domain.redis.RedisUtil;
import com.ytclub.subject.domain.service.SubjectInfoDoaminService;
import com.ytclub.subject.domain.service.SubjectLikedDomainService;
import com.ytclub.subject.infra.basic.entity.SubjectInfo;
import com.ytclub.subject.infra.basic.entity.SubjectInfoEs;
import com.ytclub.subject.infra.basic.entity.SubjectLabel;
import com.ytclub.subject.infra.basic.entity.SubjectMapping;
import com.ytclub.subject.infra.basic.service.SubjectEsService;
import com.ytclub.subject.infra.basic.service.SubjectInfoService;
import com.ytclub.subject.infra.basic.service.SubjectLabelService;
import com.ytclub.subject.infra.basic.service.SubjectMappingService;
import com.ytclub.subject.infra.entity.UserInfo;
import com.ytclub.subject.infra.rpc.UserRPC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目领域服务层实现类
 *
 * @author: HuangQi
 * @date: Created in 21:14 2023/12/19
 * @description: 题目领域服务层实现
 */
@Service
@Slf4j
public class SubjectInfoDoaminServiceImpl implements SubjectInfoDoaminService {

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private UserRPC userRPC;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";

    /**
     * 新增题目
     *
     * @param subjectInfoBO 新增题目的信息
     * @return 新增结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDoaminServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }

        // 参数转换
        SubjectInfo subjectInfo =
                SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());


        // 调用service
        subjectInfoService.insert(subjectInfo);

        // 根据题目类型插入对应的表中
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfoBO.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);

        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        // 插入题目分类关联表subjectMapping
        List<SubjectMapping> subjectMappingList = new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);

        // 同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("零の守墓人");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);

        // redis放入zadd计入排行榜
        String loginId = LoginUtil.getLoginId();
        redisUtil.addScore(RANK_KEY, loginId, 1);

    }

    /**
     * 分页查询题目
     *
     * @param subjectInfoBO 查询条件
     * @return 查询到的题目列表
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDoaminServiceImpl.getSubjectPage.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();

        // 参数转换
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);

        // 查询符合条件的题目数量
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(),
                subjectInfoBO.getLabelId());
        if (count == 0) {
            return pageResult;
        }

        // 查询符合条件的题目的详情
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(),
                subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());

        // 结果转换
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConverter.INSTANCE.convertInfoToBo(subjectInfoList);
        subjectInfoBOList.forEach(info -> {
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(info.getId());
            List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
            List<Long> labelIds = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIds);
            List<String> labelNames = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
            info.setLabelNameList(labelNames);
        });
        pageResult.setTotal(count);
        pageResult.setRecords(subjectInfoBOList);

        return pageResult;
    }

    /**
     * 查询题目详情
     *
     * @param subjectInfoBO 查询条件
     * @return 题目详情
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDoaminServiceImpl.querySubjectInfo.bo:{}", JSON.toJSONString(subjectInfoBO));
        }

        // 根据题目id查询题目详情
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());

        Integer subjectType = subjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId());

        // 结果转换
        SubjectInfoBO resultBo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);

        // 转换
        // 根据题目id查询标签id列表
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<Long> labelIdList = new ArrayList<>();
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (!CollectionUtils.isEmpty(mappingList)) {
            labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        }
        // 根据标签id查询标签
        List<SubjectLabel> labelList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(labelIdList)) {
            labelList = subjectLabelService.batchQueryById(labelIdList);
        }
        // 得到全部的标签名称
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());

        // 封装返回结果
        resultBo.setLabelNameList(labelNameList);

        resultBo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        resultBo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        assembleSubjectCursor(subjectInfoBO, resultBo);
        return resultBo;

    }

    /**
     * 组装题目游标
     *
     * @param subjectInfoBO 前端传递的bo
     * @param resultBo      返回结果bo
     */
    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO resultBo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        resultBo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        resultBo.setLastSubjectId(lastSubjectId);
    }

    /**
     * 全文检索
     *
     * @param subjectInfoBO 检索条件
     * @return 检索结果
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDoaminServiceImpl.getSubjectPageBySearch.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }


    /**
     * 获取贡献列表
     *
     * @return 贡献列表
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDoaminServiceImpl.getContributeList.typedTuples:{}", typedTuples);
        }
        // List<SubjectInfo> subjectInfoList = subjectInfoService.getContributeCount();
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach(rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRPC.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        });
        return boList;
    }


}
